package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.PlanDetail;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import org.json.JSONException;

public class DetailDelegateTaskFragment extends Fragment {
  public static final String EXTRA_DELAGATETASK =
      "com.isunland.managesystem.entity.extra_delagatetask";
  private static final int REQUEST_DELETE_TEMPPLAN = 1;
  private static final int REQUEST_CHANGE = 2;
  private PlanDetail mDelegateTask;
  private BaseVolleyActivity mActivity;
  private CurrentUser mUser;
  private EditText etEvaluteContent;
  private EditText etscore;

  // <requestFocus />
  //public interface Callback {
  //    void onRefresh();
  //}

  public static DetailDelegateTaskFragment newInstance(PlanDetail item) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_DELAGATETASK, item);
    DetailDelegateTaskFragment fragment = new DetailDelegateTaskFragment();
    fragment.setArguments(args);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {

      actionBar.setDisplayHomeAsUpEnabled(true);
      actionBar.setTitle(R.string.detaildelegateTask);
    }
    // 获取传过来的delegateTask
    mDelegateTask = (PlanDetail) getArguments().getSerializable(EXTRA_DELAGATETASK);

    mUser = CurrentUser.newInstance(getActivity());
  }

  // 添加删除按钮
  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //inflater.inflate(R.menu.menu_delete, menu);
    //删除,提交评价,退回修改
    inflater.inflate(R.menu.menu_delegate_detail, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回图标
      case android.R.id.home:

        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_change:
        // 转交考核人
        if ("noeval".equalsIgnoreCase(mDelegateTask.getEvaStatus())) {
          Intent change = new Intent(getActivity(), DelegateTaskChangeActivity.class);
          change.putExtra(DelegateTaskChangeFragment.EXTRA_ID, mDelegateTask.getId());
          startActivityForResult(change, REQUEST_CHANGE);
        } else {
          ToastUtil.show("只能转交未评价的任务!");
        }
        break;
      case R.id.menu_item_submit:
        //提交评价:  未评价或退回,已完成任务
        if (("noeval".equalsIgnoreCase(mDelegateTask.getEvaStatus()) || "backeval".equalsIgnoreCase(
            mDelegateTask.getEvaStatus())) && "已完成".equalsIgnoreCase(
            mDelegateTask.getPlanStatus())) {
          if (!TextUtils.isEmpty(etscore.getText().toString()) && !TextUtils.isEmpty(
              etEvaluteContent.getText().toString())) {
            volleyPostSubmit();
          } else {
            ToastUtil.show("请填写完整评分和评价内容！");
          }
        } else {
          ToastUtil.show("任务未完成或已评价不能评价");
        }
        break;
      case R.id.menu_item_back:
        //退回修改 :  未评价,已完成任务
        if ("noeval".equalsIgnoreCase(mDelegateTask.getEvaStatus()) && "已完成".equalsIgnoreCase(
            mDelegateTask.getPlanStatus())) {
          volleyPostBack();
        } else {
          ToastUtil.show("任务未完成或已评价不能退回");
        }
        break;
      // 响应删除菜单按钮,弹出对话框
      case R.id.menu_item_delete:

        setDeleteButtonStatus(mDelegateTask);

        break;
      default:
        return super.onOptionsItemSelected(item);
    }
    return super.onOptionsItemSelected(item);
  }

  private void setDeleteButtonStatus(PlanDetail content) {
    try {
      if (!"Temp".equalsIgnoreCase(content.getPlanKindTypeCode())) {
        //只能删除临时任务
        ToastUtil.show("只能删除临时任务");
        return;
      }

      if ("archive".equalsIgnoreCase(content.getEvaStatus()) || "eval".equalsIgnoreCase(
          content.getEvaStatus())) {
        //已评价或归档内容不允许删除
        ToastUtil.show("已评价或归档内容不允许删除");
        return;
      }

      if (!content.getRegStaffId().equalsIgnoreCase(mUser.getJobNumber())) {
        //只能删除自己登记的任务
        ToastUtil.show("只能删除自己登记的任务");
        return;
      }

      FragmentManager fm = getActivity().getSupportFragmentManager();
      DialogFragment dialog = BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);
      dialog.setTargetFragment(DetailDelegateTaskFragment.this, REQUEST_DELETE_TEMPPLAN);
      dialog.show(fm, "");
    } catch (Exception e) {
      LogUtil.e("delete button error", e);
    }
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    // 找到布局控件
    View view = inflater.inflate(R.layout.fragment_delegate_task_detail, container, false);
    TextView tv_regstaffname = (TextView) view.findViewById(R.id.tv_regStaffName);
    TextView tv_excManName = (TextView) view.findViewById(R.id.tv_excManName);
    TextView et_planContentDesc = (TextView) view.findViewById(R.id.tv_planContentDesc);
    et_planContentDesc.setEnabled(false);// 不可编辑
    TextView et_planExcDesc = (TextView) view.findViewById(R.id.tv_planExcDesc);
    et_planExcDesc.setEnabled(false);// 不可编辑
    TextView tv_planStagecompleteTime = (TextView) view.findViewById(R.id.tv_planStagecompleteTime);
    TextView tv_planEsteTime = (TextView) view.findViewById(R.id.tv_planEsteTime);
    TextView tv_rateCurrent = (TextView) view.findViewById(R.id.tv_rateCurrent);
    TextView tv_planStatus = (TextView) view.findViewById(R.id.tv_planStatus);
    // 控件填写内容
    tv_regstaffname.setText(mDelegateTask.getTaskManName());
    tv_excManName.setText(mDelegateTask.getExcManName());
    et_planContentDesc.setText(mDelegateTask.getPlanContentDesc());
    // 完成情况为空时，默认显示"计划中.."
    if (MyStringUtil.isEmpty(mDelegateTask.getPlanExcDesc())) {
      et_planExcDesc.setText("计划中...");
    } else {
      et_planExcDesc.setText(mDelegateTask.getPlanExcDesc());
    }
    tv_planStagecompleteTime.setText(mDelegateTask.getPlanStagecompleteTime());
    //要求完成时间
    //		tv_planEsteTime.setText(getString(R.string.planEsteTime,
    //				mDelegateTask.getPlanEsteTime()));
    tv_planEsteTime.setText(mDelegateTask.getPlanEsteTime());
    // 完成度为空时，默认显示0%
    if (MyStringUtil.isEmpty(mDelegateTask.getRateCurrent())) {
      tv_rateCurrent.setText("0%");
    } else {
      tv_rateCurrent.setText(mDelegateTask.getRateCurrent());
    }
    tv_planStatus.setText(mDelegateTask.getPlanStatus());

    TextView tvPlanKind = (TextView) view.findViewById(R.id.tv_planKind);
    tvPlanKind.setText(mDelegateTask.getPlanKindName());
    TextView tvPlanKindType = (TextView) view.findViewById(R.id.tv_planKindType);
    tvPlanKindType.setText(mDelegateTask.getPlanKindType());
    TextView tv_sumTime = (TextView) view.findViewById(R.id.tv_sumTime);
    tv_sumTime.setText(mDelegateTask.getWorkTime());
    TextView tv_cooperate = (TextView) view.findViewById(R.id.tv_cooperate);
    tv_cooperate.setText(mDelegateTask.getCoopManNames());
    TextView tv_registrant = (TextView) view.findViewById(R.id.tv_registrant);
    tv_registrant.setText(mDelegateTask.getRegStaffName());
    TextView tv_registerTime = (TextView) view.findViewById(R.id.tv_registerTime);

    //noinspection deprecation
    tv_registerTime.setText(
        MyDateUtil.format(MyDateUtil.parse(mDelegateTask.getRegDate()), MyDateUtil.TYPE_DATE));
    etEvaluteContent = (EditText) view.findViewById(R.id.et_evaluteContent);
    etEvaluteContent.setText(mDelegateTask.getResultDescEvalu());//评价内容
    etscore = (EditText) view.findViewById(R.id.et_score);
    etscore.setText(mDelegateTask.getResultScore());//评分
    return view;
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_DELETE_TEMPPLAN) {

      volleyPostDelete();
    }
    if (requestCode == REQUEST_CHANGE) {
      getActivity().setResult(Activity.RESULT_OK);
      getActivity().finish();
    }
  }

  private void volleyPostSubmit() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELEGATETTASK_SCORE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mDelegateTask.getId());
    params.put("content", etEvaluteContent.getText().toString());//评价内容
    params.put("score", etscore.getText().toString());//评分
    params.put("evaStatus", "eval");//评分
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse());
  }

  private void volleyPostBack() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELEGATETTASK_BACK);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mDelegateTask.getId());
    params.put("content", mDelegateTask.getId());//退回说明
    params.put("oper", "back");//操作标识，固定值
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse());
  }

  // 解析删除
  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TEMPLAN_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mDelegateTask.getId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        // 解析响应的字符串
        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {
          ToastUtil.show(R.string.failure_operation);
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          ToastUtil.show(R.string.failure_operation);
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          ToastUtil.show(R.string.success_operation);
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  public VolleyResponse getResponse() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        // 解析响应的字符串
        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {
          ToastUtil.show(R.string.failure_operation);
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          ToastUtil.show(R.string.failure_operation);
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          ToastUtil.show(R.string.success_operation);
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }
    };
  }
}
